import json
from django.contrib.auth import authenticate
from django.http.response import HttpResponse
from django.utils.encoding import force_text
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View
from ghouse import settings
from oauth2.views import ApiView, _decode_pwd
from product.models import House


class PhoneLoginView(ApiView):
    request_msg = 'login-req'
    request_sign_fields = ['msg', 'username', 'pwd', 'nonce', 'tag']
    response_sign_fields = ['msg', 'username', 'nonce', 'tag']
    response_msg = 'login-resp'

    def get_result(self, **kwargs):
        pwd = _decode_pwd(settings.TAG, kwargs['password'])
        user = authenticate(username=kwargs['username'], password=pwd)
        if user:
            return {'status': 200, 'status-text': force_text("登陆成功")}
        else:
            return {'status': 409, 'status-text': force_text("用户名或密码错误")}


class HouseRentListView(View):
    def get(self, request):
        # obj = request.POST['ghouse']
        # obj = json.loads(obj)

        data = {}
        res_data = {
            "status": 1,
            "data": [{"id": h.id, "name": h.name} for h in data],
            "msg": "rent_response"
        }
        return HttpResponse(json.dumps(res_data))

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super(HouseRentListView, self).dispatch(request, *args, **kwargs)


class HouseRentPublishView(View):
    def get(self, request):
        # obj = request.POST['ghouse']
        # obj = json.loads(obj)

        # House.objects.create()
        res_data = {
            "status": 1,
            "data": "发布成功！",
            "msg": "rent_response"
        }
        return HttpResponse(json.dumps(res_data))

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super(HouseRentPublishView, self).dispatch(request, *args, **kwargs)
